package ConnectionPool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/*
 * JDBC线程池
 * 思路：ArrayList存储大小为size的线程
 *getConnection  向外部借出线程
 *returnConnection	归还线程到List
 *init()函数为初始化进程，此处必须保证线程是活的
*/
public class ConnectionPool {
	public static String SQLLogin="jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8";
	public static String SQLUser = "root";
	public static String SQLPassword = "admin";
	
	List<Connection> cs =new ArrayList<Connection>();
	int size;
	public ConnectionPool(int size) {
		this.size = size;
		init();
	}
	
	private void init() {
		try {
			//检查驱动
			Class.forName("com.mysql.jdbc.Driver");
			//创建size个线程
			for(int i = 0;i<size;i++) {
				Connection c = DriverManager.getConnection(SQLLogin,SQLUser,SQLPassword);
				cs.add(c);
			}
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized Connection getConnection() {
		while(cs.isEmpty()) {
			try {
				this.wait();
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		Connection c = cs.remove(0);
		return c;
	}
	
	public synchronized void returnConnection(Connection c) {
		cs.add(c);
		this.notifyAll();
	}
}
